<template>
    <div class="common-layout">
        <div class="top">
            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item label="Approved by">
                    <el-input v-model="formInline.user" placeholder="Approved by" style="width: 240px;" clearable />
                </el-form-item>
                <el-form-item label="Activity zone">
                    <el-select v-model="formInline.region" placeholder="Activity zone" clearable style="width: 240px;"
                        learable>
                        <el-option label="Zone one" value="shanghai" />
                        <el-option label="Zone two" value="beijing" />
                    </el-select>
                </el-form-item>
                <el-form-item label="Activity time">
                    <el-date-picker style="width: 240px;" v-model="formInline.date" value-format="YYYY-MM-DD hh:mm:ss"
                        format="YYYY-MM-DD hh:mm:ss" type="date" placeholder="Pick a date" clearable />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="onSubmit">Query</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="top">
            <el-button type="primary" @click="godialogTableVisible('add')">新增</el-button>
            <el-button type="danger" @click="delTab">删除</el-button>
            <el-button type="warning" :disabled='!(selectable.length == 1)' @click="editTab">编辑</el-button>
            <!-- <el-upload ref="uploadRef" class="upload-demo" action="#" :show-file-list='false' :limit="1" :http-request="goUpload" :auto-upload="false">
                <el-button type="success" :icon="Upload">导入</el-button>


            </el-upload> -->
            <!-- <input type="file" accept=".xls,.xlsx" class="upload-file" @change="goUpload($event)" /> -->
            <el-button type="success" :icon="Download" @click="goDownload">下载模板</el-button>
        </div>
        <div class="center">
            <el-table :data="tableData" height="500" @selection-change="handleSelectionChange" style="width: 100%">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="user" label="姓名" width="180" />
                <el-table-column prop="name" label="Name" width="180" />
                <el-table-column prop="date" label="时间" />
                <el-table-column prop="val" label="值" />
                <el-table-column prop="val1" label="值" />
                <el-table-column prop="val2" label="值" />
                <el-table-column prop="val3" label="值" />
                <el-table-column prop="val4" label="值" />
            </el-table>
        </div>
        <div class="foot">
            <el-pagination v-model:current-page="pageSize.size" v-model:page-size="pageSize.page"
                :page-sizes="[10, 20, 50, 100]" background layout="sizes, prev, pager, next" :total="pageSize.total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
        <el-dialog v-model="dialogTableVisible" :title="dialogTable" width="1000">

            <el-form :inline="true" :model="formObj" label-width="120px" class="demo-form-inline">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="姓名">
                            <el-input v-model="formObj.user" style="width: 200px;" placeholder="Approved by"
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="Name">
                            <el-input v-model="formObj.name" style="width: 200px;" placeholder="Approved by"
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="时间">
                            <el-input v-model="formObj.date" style="width: 200px;" placeholder="Approved by"
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="值">
                            <el-input v-model="formObj.val" style="width: 200px;" placeholder="Approved by" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12"> <el-form-item label="值">
                            <el-input v-model="formObj.val1" style="width: 200px;" placeholder="Approved by"
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="值">
                            <el-input v-model="formObj.val2" style="width: 200px;" placeholder="Approved by"
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="值">
                            <el-input v-model="formObj.val3" style="width: 200px;" placeholder="Approved by"
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="值">
                            <el-input v-model="formObj.val4" style="width: 200px;" placeholder="Approved by"
                                clearable />
                        </el-form-item>
                    </el-col>
                    <el-col v-if="dialogTable == '新增'" :span="12">
                        <el-form-item label="id">
                            <el-input v-model="formObj.id" style="width: 200px;" placeholder="Approved by" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div class="dialog-foot">
                <el-button type="primary" @click="confirm">确认</el-button>
                <el-button @click="close">关闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import {
    Download,
    Upload
} from '@element-plus/icons-vue'
import * as XLSX from 'xlsx' 
import { ref, getCurrentInstance, nextTick, onMounted, } from "vue";
// const routerlist = ref<any>()
// routerlist.value = [{ name: '首页', router: 'index', id: 1 }, { name: '系统管理', router: 'system', id: 2 }, { name: '首页', router: 'systemRole', id: 3 }]
interface Person {
    user?: string,
    region?: string
    date?: string
}
interface Person1 {
    user: string,
    name: string,
    date: string,
    val: string,
    val1: string,
    val2: string,
    val3: string,
    val4: string,
    id: string
}
const formInline = ref<Person>({})
const tableData = ref<Person1[]>([])

let onSubmit = function (): void {

    console.log(formInline.value)
}
onMounted(() => {
    setTimeout(() => {
        tableData.value = [
            { user: '张三', id: '1', name: '张三1', date: '2023-10-10', val: 'val-01', val1: 'val-01', val2: 'val-01', val3: 'val-01', val4: 'val-01', },
            { user: '张三', id: '2', name: '张三1', date: '2023-10-10', val: 'val-01', val1: 'val-01', val2: 'val-01', val3: 'val-01', val4: 'val-01', },
            { user: '张三', id: '3', name: '张三1', date: '2023-10-10', val: 'val-01', val1: 'val-01', val2: 'val-01', val3: 'val-01', val4: 'val-01', },
            { user: '张三', id: '4', name: '张三1', date: '2023-10-10', val: 'val-01', val1: 'val-01', val2: 'val-01', val3: 'val-01', val4: 'val-01', },
            { user: '张三', id: '5', name: '张三1', date: '2023-10-10', val: 'val-01', val1: 'val-01', val2: 'val-01', val3: 'val-01', val4: 'val-01', },
            { user: '张三', id: '6', name: '张三1', date: '2023-10-10', val: 'val-01', val1: 'val-01', val2: 'val-01', val3: 'val-01', val4: 'val-01', },
            { user: '张三', id: '7', name: '张三1', date: '2023-10-10', val: 'val-01', val1: 'val-01', val2: 'val-01', val3: 'val-01', val4: 'val-01', },
            { user: '张三', id: '8', name: '张三1', date: '2023-10-10', val: 'val-01', val1: 'val-01', val2: 'val-01', val3: 'val-01', val4: 'val-01', },
            { user: '张三', id: '9', name: '张三1', date: '2023-10-10', val: 'val-01', val1: 'val-01', val2: 'val-01', val3: 'val-01', val4: 'val-01', },
            { user: '张三', id: '10', name: '张三1', date: '2023-10-10', val: 'val-01', val1: 'val-01', val2: 'val-01', val3: 'val-01', val4: 'val-01', },
        ]
    }, 1000);
})

//分页组件
interface page {
    page: number,
    size: number,
    total: number
}

let pageSize = ref<page>({ page: 10, size: 1, total: 100 })
// 切换条目
const handleSizeChange = function (): void {
    pageSize.value.size = 1
    console.log(pageSize.value)
}
//切换分页
const handleCurrentChange = function (): void {

    console.log(pageSize.value)
}


//新增功能
interface formType {
    user: string,
    name: string,
    date: string,
    val: string,
    val1: string,
    val2: string,
    val3: string,
    val4: string,
    id: string
}
const dialogTableVisible = ref<boolean>(false)
const dialogTable = ref<string>('')
const formObj = ref<formType>({
    user: "",
    name: "",
    date: "",
    val: "",
    val1: "",
    val2: "",
    val3: "",
    val4: "",
    id: ''
})
const selectable = ref<string[]>([])

// 点击新增事件
const godialogTableVisible = function (a: string, b?: formType): void {
    dialogTableVisible.value = true
    if (a == 'add') {
        dialogTable.value = '新增'
    } else {
        dialogTable.value = '编辑'
    }
    if (b) {
        let c: formType = JSON.parse(JSON.stringify(b))
        formObj.value = c
    }


}
//关闭事件
const close = function (): void {
    formObj.value = {
        user: "",
        name: "",
        date: "",
        val: "",
        val1: "",
        val2: "",
        val3: "",
        val4: "",
        id: ''
    }
    setTimeout(() => {
        dialogTableVisible.value = false
    }, 100)

}
//确认新增 确认编辑
const confirm = function (): void {
    if (dialogTable.value == '新增') {
        tableData.value.push(formObj.value)

    } else if (dialogTable.value == '编辑') {
        let index = tableData.value.findIndex(item => item.id == formObj.value.id)
        if (index != -1) {
            tableData.value[index] = formObj.value
        }
    }
    close()
}
//选择多选事件
const handleSelectionChange = (val: formType[]) => {
    let arr: string[] = []
    val.forEach(ele => {
        arr.push(ele.id)
    });
    selectable.value = arr



}
//删除列表数据
const delTab = (): void => {
    const tabobj = tableData.value.filter(ele => {
        return !selectable.value.includes(ele.id)
    })
    tableData.value = tabobj
    console.log(tabobj)
}
const editTab = (): void => {
    const tabobj = tableData.value.filter(ele => {
        return selectable.value.includes(ele.id)
    })
    let obj: formType = tabobj[0]
    godialogTableVisible('edit', obj)

}
//前端下载模板
const goDownload = () => {
    let a = document.createElement('a');
    a.href = '/public/导入模板.xlsx';
    //路径中'/'为根目录，即index.html所在的目录
    a.download = '导入模板.xlsx'
    a.click();

}
const upload_file = ref<string>('')
const listHead = ref<string[]>(['姓名', 'Name', '时间', '值', '值1', '值2', '值3', '值4'])
const lists = ref([])

//导入
const goUpload = (e:any) => {
    console.log(e,'files')
    const files = e.target.files;
   
    if (files.length <= 0) {
        return false;
    } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {

        // this.$Message.warning('上传格式不正确，请上传xls或者xlsx格式');
        return false;
    } else {
        // 更新获取文件名
        upload_file.value = files[0].name;
    }
    console.log(files,'files')

    const fileReader = new FileReader();
    fileReader.onload = ev => {
        try {
            const data = ev.target?.result;
            // console.log( 'data',data)
            const workbook = XLSX.read(data, {
                type: "binary", cellDates: true
            });
            console.log(workbook, 'wsname')
            const wsname = workbook.SheetNames[0]; //取第一张表
            const header = getHeaderRow(workbook.Sheets[wsname]);
            console.log("读取的excel表头数据（第一行）", header);
            if (JSON.stringify(header) == JSON.stringify(listHead.value)) {
                const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);
                console.log(ws, 'ws')
                lists.value = JSON.parse(JSON.stringify(ws)) //解析出来的数据
                // that.assemblyData()
            } else {
                // that.$Message.error('导入表格和初始模板不同,请下载模板重新导入');
                // that.clearImport()
            }
        } catch (e) {
            console.log(e, 'error')
            return false;

        }
    };
    fileReader.readAsBinaryString(files[0]);

}
//获取表头数据
const getHeaderRow = (sheet:any):string[] => {
    const headers = []; // 定义数组，用于存放解析好的数据
    const range = XLSX.utils.decode_range(sheet["!ref"]); // 读取sheet的单元格数据
    let C;
    const R = range.s.r;
    /* start in the first row */
    for (C = range.s.c; C <= range.e.c; ++C) {
        /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })];
        /* find the cell in the first row */
        let hdr = "UNKNOWN " + C; // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell);
        headers.push(hdr);
    }
    return headers; // 经过上方一波操作遍历，得到最终的第一行头数据
}
</script>
<style scoped lang="scss">
.common-layout {
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
    background-color: #fff;

    .top {
        width: 100%;
        padding: 10px 10px;
    }

    .center {
        padding: 0 10px;
    }

    .foot {
        height: 40px;
        margin: 10px 30px;
        float: right;
        // min-height: 100px;
        // background-color: #f0f;
    }

    .dialog-foot {
        display: flex;
        justify-content: right;
    }
}
</style>
